<?php

include('wt_config.inc.php');
include(WT_DIR . '/utility.inc.php');
include(WT_DIR . '/db.inc.php');
include(WT_DIR . '/glitz/header.inc.php');

if (!isset($_SERVER['PHP_AUTH_USER']) || !$_SERVER['PHP_AUTH_USER']) {
    die('Unauthorized access.');
}
$status = false; // false means no error messages
$action = rv('action', 'main');
$next = false; // chaining commands

if ($action == 'update') {
    /* handle db updates before writing page */
    $action = 'main'; // will return to main page after update
    $what = rv('what');
    if (!$what) {
        die('update called without specifying one of item, sfx, or txt');
    }
    switch ($what) {
        case 'item':
            $id = rv('id');
            if (!$id) {
                die('update item called with no id specified');
            }
            $status = update_item($id);
            echo('<p>Saved. <a href="?action=edit&amp;what=item&amp;id=' . $id . '">Re-edit ' . htmlentities($_POST['T']) . '</a>');
            break;
        case 'sfx':
            $id = rv('id');
            if (!$id) {
                die('update SFX called with no id specified');
            }
            $status = update_sfx($id);
            $ruleset = get_record($id);
            echo('<p>Saved. <a href="?action=edit&amp;what=sfx&amp;id=' . $id . '">Re-edit ' . htmlentities($ruleset['title']) . '</a>');
            break;
        case 'txt':
            $file = rv('file');
            $status = update_txt($file);
            echo('<p>Saved. <a href="?action=edit&amp;what=txt&amp;file=' . $file . '">Re-edit ' . $file . '</a>');
            break;
        default:
            die('update called without specifying one of item, sfx, or txt');
    }
}

if ($action == 'edit') {
    /* display appropriate form */
    $what = rv('what');
    if (!$what) {
        die('edit called without specifying item, sfx, or txt');
    }
    $inc = WT_DIR . '/forms/' . $what . '.inc.php';
    if (file_exists($inc)) {
        include($inc);
    }
}

if ($action == 'restore') {
    include('restore.inc.php');
}

if ($action == "sfxgen") {
    $output = array();
    echo('<p>Extracting records from SFX...</p>');
    ob_flush();
    chdir(WT_DIR . '/SFX_SCRIPTS');
    exec(SFX_EXTRACT_SCRIPT, $output);
    if ($output) {
        echo("<p>Failed to extract SFX:</p><pre>" . implode("\n", $output) . '</pre>');
    } else {
        echo('<p>Importing to database...</p>');
        ob_flush();
        importSFX();
        echo('<p>Done.</p>');
        $action = "view";
        $_REQUEST['file'] = 'sfx';
    }
}

if ($action == 'ezgen') {
    echo('<p>Generating EZproxy configuration...</p>');
    ob_flush();
    $log = array();
    gen_ez_cfg($log);
    echo('<p>Done.</p>');
    $action = "view";
    $_REQUEST['file'] = 'generated';
}

if ($action == 'tamale_lite') {
    echo('<p>Generating EZproxy configuration...</p>');
    ob_flush();
    $log = array();
    gen_ez_cfg($log);
    echo('<p>Done.</p>');
    $action = 'commit';
    $next = 'restartez';
}

if ($action == 'tamale') {
    $output = array();
    if (SFX_ENABLED) {
        echo('<p>Extracting records from SFX...</p>');
        ob_flush();
        chdir(WT_DIR . '/SFX_SCRIPTS');
        exec(SFX_EXTRACT_SCRIPT, $output);
        if ($output) {
            echo("<p>Failed to extract SFX:</p><pre>" . implode("\n", $output) . '</pre>');
        } else {
            echo('<p>Importing to database...</p>');
            ob_flush();
            importSFX();
            echo('<p>Done.</p>');
        }
    }
    if (!$output) {
        echo('<p>Generating EZproxy configuration...</p>');
        ob_flush();
        $log = array();
        gen_ez_cfg($log);
        echo('<p>Done.</p>');
        $action = 'commit';
        $next = 'restartez';
    }
}

if ($action == 'commit') {
    //replace active config with last generated
    if (md5(file_get_contents(EZCONFIG)) == md5(file_get_contents(EZCONFIG_DIR . 'config.txt'))) {
        echo('<p>Last generated configuration and currently running configuration are the same, doing nothing.</p>');
    } else {
        $backup = BACKUP_DIR . 'config/config.txt-' . date('Ymd-his');
        if (file_exists(EZCONFIG) && !@copy(EZCONFIG, $backup)) {
            echo('<p>Failed to copy current configuration to backup (check permissions?). Configuration is unchanged.</p>');
        } else {
            if (!@unlink(EZCONFIG)) {
                echo('<p>Failed to remove currently running configuration at ' . EZCONFIG . ' (check permissions?)</p>');
                unlink($backup);
            } else {
                if (!@copy(EZCONFIG_DIR . 'config.txt', EZCONFIG)) {
                    echo('<p>Failed to copy new configuration to active. Restoring from backup.</p>');
                    if (!@copy($backup, EZCONFIG)) {
                        echo('<p style="color:red">FAILED TO RESTORE BACKUP TO ACTIVE!</p>');
                    } else {
                        echo('<p>Restored backup.</p>');
                    }
                } else {
                    echo('<p>Configuration replaced. Old configuration has been saved as ' . $backup . '.</p>');
                }
            }
        }
    }
    if ($next) {
        $action = $next;
    } else {
        $action = 'main';
    }
}

if ($action == "restartez") {
    echo('<p>Restarting EZproxy, please wait...</p>');
    ob_flush();
    $output = exec(EZ_RESTART_COMMAND, $rv);
    if ($rv) {
        echo('<p style="color:red">Failed to restart.<br />Command: ' . EZ_RESTART_COMMAND . ' Failed with error code ' . (1 * $rv)
        . '<br/>Output:<pre>' . implode("\n", $output) . '</pre>');
    } else {
        echo('<p>Restarted.</p>');
    }
    $action = 'main';
}

if ($action == 'view') {
    include('view.inc.php');
}

if ($action == 'main') {
    $inc = WT_DIR . '/forms/main.inc.php';
    if (file_exists($inc)) {
        include($inc);
    }
}

include(WT_DIR . '/glitz/footer.inc.php');
